package com.jnxx.task.taskRemind;

import com.jnxx.task.controller.WechatController;
import com.jnxx.task.domain.OkrStaff;
import com.jnxx.task.domain.Task;
import com.jnxx.task.mapper.OkrStaffMapper;
import com.jnxx.task.mapper.TaskMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class MessageConsumer {
    public  static ExecutorService executorService = Executors.newFixedThreadPool(5);

    @Autowired
    MessageDelyQueueService delyQueueService;

    @Autowired
    private WechatController wechatController;

    @Autowired
    private OkrStaffMapper staffMapper;

    @Autowired
    private TaskMapper taskMapper;

    private boolean stopFlag=false;

    public void setStopFlag(boolean stopFlag) {
        this.stopFlag = stopFlag;
    }
    // 周一至周五，早上9点开启 开启延迟任务
    @Scheduled(cron = "0 0 10 * * MON-FRI")
    public void startDelayTask(){
        System.out.println("开启延迟任务");
        setStopFlag(false);
    }

    // 周一至周五，晚上20点关闭 关闭延迟任务
    @Scheduled(cron = "0 0 20 * * MON-FRI")
    public void closeDelayTask(){
        System.out.println("关闭延迟任务");
        setStopFlag(true);
    }

    @SneakyThrows
    public void consumer(){
        log.info("Executor Service Status: Terminated={}, Shutdown={}", executorService.isTerminated(), executorService.isShutdown());
        executorService.execute(() -> {
            try {
                while (!stopFlag) {
                    List<Long> taskIds = delyQueueService.pull();
                    if (taskIds.size() == 0) {
                        try {
                            // 5分组扫描一次
//                            Thread.sleep(10000 );
                            Thread.sleep(60000 * 5);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        handleMessage(taskIds);
                    }
                }
            } catch (Exception e) {
                log.error("Exception in async task", e);
            }
        });
    }

    /**
     * 消息处理
     * @param taskIds
     */
    public void  handleMessage( List<Long> taskIds){
        log.info("进入handleMessage");
        log.info("参数：{}", taskIds);
        try {
            if (taskIds.size() > 0){
                for (Long taskId : taskIds) {
                    Task task = taskMapper.findOne(taskId);
                    if (task == null){
                        this.delyQueueService.remove(taskId);
                    }
                    assert task != null;
                    // 未接收 或者 未完成
                    if (!"1".equals(task.getSureState()) || !task.getStates()){

                        HashMap<String,String> map = new HashMap<>();
                        OkrStaff one = staffMapper.findOne(task.getStaffId());
                        map.put("touser", one.getUserId());
                        // 还未接收
                        if (!"1".equals(task.getSureState())){
                            map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的任务还未接收，请点击查看</div><div class=\"highlight\">任务发布人："+ one.getName() +"，任务名称："+ task.getTaskName() +"</div>");
                        } else{
                            // 还未完成
                            map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您的任务还未完成，请点击查看</div><div class=\"highlight\">任务发布人："+ one.getName() +"，任务名称："+ task.getTaskName() +"</div>");
                        }
                        wechatController.sendMessage(map);
                        String taskLevel = task.getTaskLevel();
                        int dely = 0;
                        if ("最高".equals(taskLevel)){
//                          dely = 20;
                            dely = 3600;
                        } else if ("较高".equals(taskLevel)){
                            dely = 3600 * 2;
                        } else if ("普通".equals(taskLevel)){
                            dely = 3600 * 3;
                        } else if ("较低".equals(taskLevel)){
                            dely = 3600 * 5;
                        }
                        // 先将原来的删除
                        this.delyQueueService.remove(taskId);
                        // 在放入最新的
                        this.delyQueueService.pushMessage(taskId, dely);
                    }else {
                        this.delyQueueService.remove(taskId);
                    }
                }
            }
        } catch (Exception e) {
            log.error("处理消费异常:", e);
            throw new RuntimeException(e);
        }

    }
}
